import 'package:flutter/material.dart';
import 'dart:convert';
import 'dart:ui';
import 'package:dio/dio.dart';
import '../../base/constant.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import '../../http/Api.dart';
import '../../http/HttpUtil.dart';
import '../../entity/point_cate_model.dart';
import '../../entity/point_list.model.dart';
// import 'package:flutter_yres/pages/shop/pdd_detail_page.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter_easyrefresh/material_footer.dart';
import 'package:flutter_easyrefresh/material_header.dart';
import '../../util/SignUtil.dart';
import './point_detail.dart';
import '../../entity/goods_list_entity.dart';

class PointSubPage extends StatefulWidget {
  String cat_id;
  PointSubPage({
    Key key,
    this.cat_id,
  }) : super(key: key);

  @override
  _PointSubPageState createState() => _PointSubPageState();
}

class _PointSubPageState extends State<PointSubPage> {
  EasyRefreshController _controller = new EasyRefreshController();
  List<PointCateModelData> subs = []; //拼多多子级分类数组
  int page = 1;
  var search = '';
  List<PddListModelData> shopData = []; //拼多多商品

  double _listHeight = ScreenUtil.getInstance().setHeight(240); //单个列表高度

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      child: _buildSub(),
    );
  }

  //其他类别主页内容
  Widget _buildSub() {
    return Container(
      child: new EasyRefresh(
        //刷新  加载组件
        enableControlFinishRefresh: true,
        enableControlFinishLoad: true,
        controller: _controller,
        header: MaterialHeader(),
        footer: MaterialFooter(),
        child: CustomScrollView(slivers: <Widget>[
          SliverGrid(
            gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
              maxCrossAxisExtent: (ScreenUtil.getInstance().setWidth(750) -
                      ScreenUtil.getInstance().setWidth(20)) /
                  5,
              mainAxisSpacing: 8.0,
              crossAxisSpacing: 10.0,
              childAspectRatio: 0.85, //子控件宽高比
            ),
            delegate: SliverChildBuilderDelegate(
              (BuildContext context, int index) {
                return _itemBuilder(context, subs[index]);
              },
              childCount: subs.length,
            ),
          ),
          // SliverToBoxAdapter(
          //   child: Container(
          //       height: ScreenUtil.getInstance().setHeight(60),
          //       child: Column(
          //         children: <Widget>[_buildPopHeader()],
          //       )),
          // ),
          SliverFixedExtentList(
              delegate: SliverChildBuilderDelegate(_buildListItem,
                  childCount: shopData.length),
              itemExtent: _listHeight),
        ]),
        onRefresh: () async {
          page = 1;
          getPDDShopList();
        },
        onLoad: () async {
          page++;
          getPDDShopList();
        },
      ),
    );
  }

  Widget _itemBuilder(BuildContext context, item) {
    return InkWell(
      onTap: () {
        print(item.name);
        setState(() {
          page = 1;
          search = item.name;
          getPDDShopList();
        });
      },
      child: Column(
        children: <Widget>[
          Container(
            height: ScreenUtil.getInstance().setWidth(20),
          ),
          item.icon == null || item.icon == ''
              ? Image.asset(
                  'images/logo.png',
                  fit: BoxFit.fill,
                  width: ScreenUtil.getInstance().setWidth(85),
                  height: ScreenUtil.getInstance().setWidth(85),
                )
              : CachedNetworkImage(
                  width: ScreenUtil.getInstance().setWidth(85),
                  height: ScreenUtil.getInstance().setWidth(85),
                  fit: BoxFit.fill,
                  imageUrl: Api.BaseUrl + item.icon,
                  placeholder: (context, url) => Image.asset(
                    'images/logo.png',
                    fit: BoxFit.fill,
                    width: ScreenUtil.getInstance().setWidth(85),
                    height: ScreenUtil.getInstance().setWidth(85),
                  ),
                  errorWidget: (context, url, error) => Image.asset(
                    'images/logo.png',
                    fit: BoxFit.fill,
                    width: ScreenUtil.getInstance().setWidth(85),
                    height: ScreenUtil.getInstance().setWidth(85),
                  ),
                ),
          Text(item.name,
              style: TextStyle(), maxLines: 1, overflow: TextOverflow.ellipsis),
        ],
      ),
    );
  }

//条件筛选头部
  _buildPopHeader() {
    return Container(
      height: ScreenUtil.getInstance().setHeight(60),
      width: ScreenUtil.getInstance().setWidth(750),
      child: Row(
        children: <Widget>[
          Expanded(
              flex: 1,
              child: Center(
                  child: FlatButton(
                      onPressed: () {},
                      child: Row(
                        children: <Widget>[
                          Text(
                            "综合",
                            style: TextStyle(
                                fontSize:
                                    ScreenUtil.getInstance().setWidth(25)),
                          ),
                          Icon(
                            Icons.sort,
                            size: ScreenUtil.getInstance().setWidth(28),
                          )
                        ],
                      )))),
          Expanded(
              flex: 1,
              child: Center(
                  child: FlatButton(
                      onPressed: () {},
                      child: Row(
                        children: <Widget>[
                          Text(
                            "销量",
                            style: TextStyle(
                                fontSize:
                                    ScreenUtil.getInstance().setWidth(25)),
                          ),
                          Icon(
                            Icons.sort,
                            size: ScreenUtil.getInstance().setWidth(28),
                          )
                        ],
                      )))),
          Expanded(
              flex: 1,
              child: Center(
                  child: FlatButton(
                      onPressed: () {},
                      child: Row(
                        children: <Widget>[
                          Text(
                            "价格",
                            style: TextStyle(
                                fontSize:
                                    ScreenUtil.getInstance().setWidth(25)),
                          ),
                          Icon(
                            Icons.sort,
                            size: ScreenUtil.getInstance().setWidth(28),
                          )
                        ],
                      )))),
          Expanded(
              flex: 1,
              child: Center(
                  child: FlatButton(
                      onPressed: () {},
                      child: Row(
                        children: <Widget>[
                          Text(
                            "佣金",
                            style: TextStyle(
                                fontSize:
                                    ScreenUtil.getInstance().setWidth(25)),
                          ),
                          Icon(
                            Icons.sort,
                            size: ScreenUtil.getInstance().setWidth(28),
                          )
                        ],
                      )))),
        ],
      ),
    );
  }

  Widget _buildListItem(BuildContext context, int index) {
    return new GestureDetector(
        onTap: () {
         GoodsModelData model =new GoodsModelData();
         model.goods_id = shopData[index].goods_id.toString();
         model.img = shopData[index].img;
          Navigator.of(context).push(new MaterialPageRoute(builder: (context) {
            return PointGoodsDetailPage(
              goods_id: model.goods_id,
              img: model.img,
            );
          }));
        },
        child: Container(
            margin: EdgeInsets.fromLTRB(
                0, ScreenUtil.getInstance().setHeight(15), 0, 0),
            child: Column(
              children: <Widget>[
                Row(children: <Widget>[
                  _leftImage(index),
                  Expanded(
                    child: _rightColumn(index),
                  )
                ], crossAxisAlignment: CrossAxisAlignment.start),
                Divider(
                  height: 1,
                )
              ],
            )));
  }

  Widget _pd(Widget w, {double l, double t, double r, double b}) {
    //边距
    return Padding(
        padding: EdgeInsets.fromLTRB(
            ScreenUtil.getInstance().setWidth(l) ?? 0,
            ScreenUtil.getInstance().setHeight(t) ?? 0,
            ScreenUtil.getInstance().setWidth(r) ?? 0,
            ScreenUtil.getInstance().setHeight(b) ?? 0),
        child: w);
  }

  Widget _leftImage(int index) {
    PddListModelData model = shopData[index];
    //左图
    var image = CachedNetworkImage(
      width: ScreenUtil.getInstance().setHeight(180),
      height: ScreenUtil.getInstance().setHeight(180),
      fit: BoxFit.fill,
      imageUrl: Api.ImgBaseUrl+ model.img,
      placeholder: (context, url) => Image.asset(
        'images/pic_default.png',
        width: ScreenUtil.getInstance().setHeight(180),
        height: ScreenUtil.getInstance().setHeight(180),
        fit: BoxFit.fill,
      ),
      errorWidget: (context, url, error) => Image.asset(
        'images/pic_default.png',
        width: ScreenUtil.getInstance().setHeight(180),
        height: ScreenUtil.getInstance().setHeight(180),
        fit: BoxFit.fill,
      ),
    );
    return _pd(image, l: 20, t: 0, r: 5, b: 40);
  }

  Widget _rightColumn(int index) {
    PddListModelData model = shopData[index];
    //右内容
    var title = Text(
      model.goods_name,
      style: TextStyle(
          color: Colors.black, fontSize: ScreenUtil.getInstance().setSp(26)),
      maxLines: 2,
      overflow: TextOverflow.ellipsis,
    );
    var price = RichText(
      text: TextSpan(style: TextStyle(color: Colors.red), children: [
        TextSpan(text: '¥', style: TextStyle(fontSize: 12.0)),
        TextSpan(text: model.price, style: TextStyle(fontSize: 18.0)),
        TextSpan(
          text: model.old_price,
          style: TextStyle(
              fontSize: 12.0,
              color: Colors.grey,
              decoration: TextDecoration.lineThrough,
              decorationColor: Colors.grey),
        ),
      ]),
      maxLines: 1,
      overflow: TextOverflow.ellipsis,
    );
    var volume = Container(
      child: Text('销量',
          style: TextStyle(
              color: Colors.grey,
              fontSize: ScreenUtil.getInstance().setSp(24))),
    );
    var quanHeader = Container(
      width: ScreenUtil.getInstance().setWidth(40),
      height: ScreenUtil.getInstance().setWidth(34),
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage("images/item_youhuiquan_header.png"),
          fit: BoxFit.cover,
        ),
      ),
    );
    // var quan = Container(
    //   width: ScreenUtil.getInstance().setWidth(70),
    //   height: ScreenUtil.getInstance().setWidth(34),
    //   decoration: BoxDecoration(
    //     image: DecorationImage(
    //       image: AssetImage("images/item_youhuiquan_footer.png"),
    //       fit: BoxFit.cover,
    //     ),
    //   ),
    //   child: Center(
    //       child: Text(
    //     (model.coupon_discount / 100).toString() + '元',
    //     style: TextStyle(color: Colors.white, fontSize: ScreenUtil.getInstance().setSp(24)),
    //   )),
    // );
    // var yongjin = Container(
    //   margin: EdgeInsets.fromLTRB(ScreenUtil.getInstance().setWidth(20), 0, ScreenUtil.getInstance().setWidth(20), 0),
    //   height: ScreenUtil.getInstance().setWidth(34),
    //   color: Color.fromRGBO(250, 226, 226, 1),
    //   child: Center(
    //       child: Text(
    //           '预估赚¥' +
    //               (((model.min_group_price - model.coupon_discount) *
    //                           (model.promotion_rate / 1000)) /
    //                       100)
    //                   .toStringAsFixed(2),
    //           style: TextStyle(color: Colors.red, fontSize: ScreenUtil.getInstance().setSp(24)))),
    // );
    return new Column(
      children: <Widget>[
        _pd(title, l: 10, t: 0, r: 10, b: 8),
        _pd(volume, l: 10, t: 0, r: 10, b: 8),
        _pd(price, l: 10, t: 0, r: 10, b: 8),
        Container(
          margin: EdgeInsets.all(ScreenUtil.getInstance().setWidth(5)),
          child: Row(
            children: <Widget>[
              // Expanded(
              //   flex: 1,
              //   child: Row(
              //     children: <Widget>[quanHeader, quan],
              //   ),
              // ),
              // Expanded(flex: 2, child: yongjin)
            ],
          ),
        )
        // Row(
        //   children: <Widget>[_pd(price, l: 10, t: 0, r: 10, b: 8), distance],
        // ),
        // _pd(address, l: 10, t: 0, r: 10, b: 8)
      ],
      crossAxisAlignment: CrossAxisAlignment.start,
    );
  }

  @override
  void initState() {
    _controller.finishLoad();
    _controller.finishRefresh();
    setState(() {
      page = 1;
    });
    getPDDSubCatList(widget.cat_id);
    super.initState();
  }

/*子级列表*/
  getPDDSubCatList(String pdd_id) async {
    FormData data = new FormData.fromMap({'pid': widget.cat_id});
    Response<String> response =
        await HttpUtil().post(Api.URL_POINTGOODSCAT_SubLIST, data: data);
    Map userMap = json.decode(response.data);
    print('=====自己=======');
    print(userMap);
    PointCateModelEntity itemEntity =
        new PointCateModelEntity.fromJson(userMap);
    if (itemEntity.code == 1 && mounted) {
      setState(() {
        page = 1;
        subs.clear();
        subs = itemEntity.data;
        if (subs.length > 0) {
          search = subs[0].cat_id;
          getPDDShopList();
        } else {
          search = widget.cat_id;
          getPDDShopList();
        }
      });
    }
  }

  getPDDShopList() async {
    Map map = new Map();
    map["p"] = page;
    map["per"] = "10";
    map["cat_id"] = '1';
    print(map);
    FormData data = FormData.fromMap(new Map<String, dynamic>.from(map));
    Response<String> response =
        await HttpUtil().post(Api.URL_POINTGOODS_LIST, data: data);
    Map userMap = json.decode(response.data);
    PddListModelEntity itemEntity = new PddListModelEntity.fromJson(userMap);
    print(userMap);
    if (itemEntity.code == 1 && mounted) {
      setState(() {
        if (page == 1) {
          shopData.clear();
          shopData = itemEntity.data;
          _controller.finishRefresh();  
        } else {
          shopData.addAll(itemEntity.data);
        }
        _controller.finishLoad();
      });
    } else {
      setState(() {
        _controller.finishLoad();
        _controller.finishRefresh();
      });
    }
  }
}
